package com.xinchuang.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinchuang.comment.R;
import com.xinchuang.entity.Role;
import com.xinchuang.entity.User;
import com.xinchuang.entity.UserRole;
import com.xinchuang.mapper.RoleMapper;
import com.xinchuang.mapper.UserMapper;
import com.xinchuang.mapper.UserRoleMapper;
import com.xinchuang.service.RedisUseService;
import com.xinchuang.service.UserService;
import com.xinchuang.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final UserMapper userMapper;

    private final UserRoleMapper userRoleMapper;

    private final RoleMapper roleMapper;

    private final RedisUseService redisUseService;

    @Override
    public String user(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String id = jsonObject.getString("id");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        User user = userMapper.selectOne(queryWrapper);

        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id", id);
        UserRole userRole = userRoleMapper.selectOne(userRoleQueryWrapper);
//        Role role = roleMapper.selectById(userRole.getRoleId());
        if (null != user) {
            JSONObject userJson = new JSONObject();
            userJson.put("account", user.getAccount());
            userJson.put("id", id);
            userJson.put("password", user.getPassword());
            userJson.put("passwordAgin", user.getPassword());
            userJson.put("phone", user.getPhone());
            userJson.put("remark", user.getRemark());
            userJson.put("role", userRole.getRoleId());
            userJson.put("unit", user.getUnit());
            userJson.put("userName", user.getUsername());
            userJson.put("xName", user.getName());
            return JSON.toJSONString(R.data(userJson));
        } else {
            return JSON.toJSONString(R.success("无数据"));
        }
    }

    @Override
    public String userList(JSONObject jsonObject) {
        //jsonobject解析获取页码
        String pageNum = jsonObject.getString("pageNum");
        //jsonobject解析获取页容
        String pageSize = jsonObject.getString("pageSize");
        //jsonobject解析获取关键字
        String keyword = jsonObject.getString("keyword");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(pageNum)) {
            pageNum = "1";
        }
        if (StringUtils.isNotEmpty(keyword)) {
            queryWrapper.like("username", keyword);
        }
        queryWrapper.orderByDesc("create_time");
        Page<User> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        IPage<User> iPage = userMapper.selectPage(page, queryWrapper);
        List<User> users = iPage.getRecords();
        JSONArray usersJsonArray = new JSONArray();
        if (null != users && users.size() > 0) {
            for (User user : users) {
                JSONObject userJson = new JSONObject();
                userJson.put("id", user.getId());
                userJson.put("unit", user.getUnit());
                userJson.put("phone", user.getPhone());
                userJson.put("xName", user.getName());
                userJson.put("createTime", sdf.format(user.getCreateTime()));
                userJson.put("userName", user.getUsername());
                User createUser = userMapper.selectById(user.getCreatePersion());
                userJson.put("createName", createUser == null ? "" : createUser.getName());
                QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
                userRoleQueryWrapper.eq("user_id", user.getId());
                UserRole userRole = userRoleMapper.selectOne(userRoleQueryWrapper);
                userJson.put("role", userRole.getRoleId());
                usersJsonArray.add(userJson);
            }
        }
        JSONObject userInfoJson = new JSONObject();
        userInfoJson.put("userList", usersJsonArray);
        userInfoJson.put("total", iPage.getTotal());
        userInfoJson.put("pageNum", pageNum);
        userInfoJson.put("pageSize", pageSize);
        userInfoJson.put("pageAll", Math.ceil(iPage.getTotal() * 1.0 / Long.valueOf(pageSize)));
        return JSON.toJSONString(R.data(userInfoJson));
    }

    @Override
    public String updateUser(JSONObject jsonObject, String userId) {
        //jsonobject解析获取标识
        String id = jsonObject.getString("id");
        //jsonobject解析获取用户名
        String userName = jsonObject.getString("userName");
        //jsonobject解析获取姓名
        String xName = jsonObject.getString("xName");
        //jsonobject解析获取类型
        String role = jsonObject.getString("role");
        //jsonobject解析获取单位
        String unit = jsonObject.getString("unit");
        //jsonobject解析获取联系方式
        String phone = jsonObject.getString("phone");
        //jsonobject解析获取登录账号
        String account = jsonObject.getString("account");
        //jsonobject解析获取登录密码
        String password = jsonObject.getString("password");
        //jsonobject解析获取确认密码
        String passwordAgin = jsonObject.getString("passwordAgin");
        //jsonobject解析获取备注
        String remark = jsonObject.getString("remark");
        //如果id为空则为注册，判断密码是否一致
        if (!password.equals(passwordAgin)) {
            return JSON.toJSONString(R.fail("密码不一致"));
        }
        User old = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, userName));
        //如果一致进行用户注册
        boolean ifAdd = false;
        User user = new User();
        if (StringUtils.isEmpty(id) || id.equals("0")) {
            if (ObjectUtil.isNotNull(old)) {
                return JSON.toJSONString(R.fail("用户名已存在"));
            }
            user.setCreateTime(new Date());
            user.setCreatePersion(redisUseService.getUserId(userId));
            userMapper.insert(user);
            ifAdd = true;
        } else {
            if (ObjectUtil.isNotNull(old) && !old.getId().equals(id)) {
                return JSON.toJSONString(R.fail("用户名已存在"));
            }
            user.setId(id);
        }
        user.setUsername(userName);
        user.setName(xName);
        user.setUnit(unit);
        user.setPhone(phone);
        user.setPassword(password);
        user.setAccount(account);
        user.setRemark(remark);
        user.setUpdateTime(new Date());
        userMapper.updateById(user);
        //添加权限
        UserRole userRole = userRoleMapper.selectOne(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()));
        if (ObjectUtil.isNull(userRole)) {
            userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(role);
            userRoleMapper.insert(userRole);
        } else {
            userRole.setUserId(user.getId());
            userRole.setRoleId(role);
            userRoleMapper.update(userRole, new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()));
        }
        if (ifAdd) {
            return JSON.toJSONString(R.success("用户信息新增成功"));
        } else {
            return JSON.toJSONString(R.success("用户信息更新成功"));
        }
    }

    @Override
    public String deleteUser(JSONObject jsonObject) {
        //jsonobject解析获取标识列表
        JSONArray ids = jsonObject.getJSONArray("ids");
        String idString = JSONObject.toJSONString(ids, SerializerFeature.WriteClassName);
        List<String> idList = JSONObject.parseArray(idString, String.class);
        if (ids.size() > 0) {
            userMapper.deleteBatchIds(idList);
            return JSON.toJSONString(R.success("注销成功"));
        }
        return JSON.toJSONString(R.success("无数据"));
    }

}
